package com.service.impl;

import com.Exception.NormalException.FileExceptions.FileFormatException;
import com.config.FileConfigure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

@Service
public class FileService {
    @Autowired
    private FileConfigure fileConfigure;

    // 返回保存文件的url
    public String saveFile(MultipartFile multipartFile, String dir, String fileName, boolean withPost) throws FileFormatException, IOException {
        String parent = this.fileConfigure.getBasePath() + dir;
        File parentFile = new File(parent);
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }
        String originName = multipartFile.getOriginalFilename();
        String[] names = originName.split("\\.");
        if(withPost) {
            names = fileName.split("\\.");
        }
        if(names.length != 2) {
            // throw new FileFormatException();
            StringBuilder tmp = new StringBuilder();
            for(int i = 0; i < names.length - 1; i++) {
                if(i != 0) {
                    tmp.append(".");
                }
                tmp.append(names[i]);
            }
            names[0] = tmp.toString();
            names[1] = names[names.length - 1];
            names = Arrays.copyOf(names, 2);
        }
        if(fileName != null && !withPost) {
            names[0] = fileName;
        }
        String name = name = names[0] + "." +names[1];;
        File file = new File(parent + name);
        int tmp = 1;
        while(file.isFile()) {
            name = names[0] + "(" + tmp + ")." + names[1];
            file = new File(parent + name);
            tmp++;
        }
        file.createNewFile();
        multipartFile.transferTo(file);
        return dir + name;
    }

    public String saveFile(MultipartFile multipartFile, String dir) throws FileFormatException, IOException {
        return saveFile(multipartFile, dir, null, false);
    }
}
